/**
 * 商品分类页面逻辑
 */

class ProductsPage {
    constructor() {
        this.currentCategory = '';
        this.currentPage = 1;
        this.pageSize = 12;
        this.totalPages = 1;
        this.currentView = 'grid';
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadProducts();
        this.updateUserStatus();
    }

    // 绑定事件
    bindEvents() {
        // 分类筛选
        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.handleCategoryFilter(e.target.dataset.category);
            });
        });

        // 视图切换
        document.querySelectorAll('.view-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.handleViewChange(e.target.dataset.view);
            });
        });

        // 分页
        document.getElementById('prevPage').addEventListener('click', () => {
            this.handlePageChange(this.currentPage - 1);
        });

        document.getElementById('nextPage').addEventListener('click', () => {
            this.handlePageChange(this.currentPage + 1);
        });

        // 搜索
        document.getElementById('searchBtn').addEventListener('click', () => {
            this.handleSearch();
        });

        document.getElementById('searchInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.handleSearch();
            }
        });

        // 用户认证
        this.bindAuthEvents();
    }

    // 绑定认证事件
    bindAuthEvents() {
        // 登录按钮
        document.getElementById('loginBtn').addEventListener('click', () => {
            this.showLoginModal();
        });

        // 注册按钮
        document.getElementById('registerBtn').addEventListener('click', () => {
            this.showRegisterModal();
        });

        // 模态框关闭
        document.getElementById('closeLoginModal').addEventListener('click', () => {
            this.hideLoginModal();
        });

        document.getElementById('closeRegisterModal').addEventListener('click', () => {
            this.hideRegisterModal();
        });

        // 切换模态框
        document.getElementById('switchToRegister').addEventListener('click', () => {
            this.hideLoginModal();
            this.showRegisterModal();
        });

        document.getElementById('switchToLogin').addEventListener('click', () => {
            this.hideRegisterModal();
            this.showLoginModal();
        });

        // 表单提交
        document.getElementById('loginForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleLogin();
        });

        document.getElementById('registerForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleRegister();
        });

        // 退出登录
        document.getElementById('logoutBtn').addEventListener('click', () => {
            this.handleLogout();
        });
    }

    // 处理分类筛选
    handleCategoryFilter(category) {
        // 更新按钮状态
        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelector(`[data-category="${category}"]`).classList.add('active');

        // 更新当前分类
        this.currentCategory = category;
        this.currentPage = 1;

        // 更新页面标题
        this.updatePageTitle(category);

        // 重新加载商品
        this.loadProducts();
    }

    // 更新页面标题
    updatePageTitle(category) {
        const categoryNames = {
            '': '全部商品',
            'Food': '食品',
            'Clothing': '服装',
            'Book': '图书',
            'Electronic Products': '电子产品',
            'Daily product': '日用品'
        };

        const categoryName = categoryNames[category] || '全部商品';
        document.getElementById('categoryName').textContent = categoryName;
        document.getElementById('pageTitle').textContent = categoryName;
        document.getElementById('pageDescription').textContent = `浏览${categoryName}分类的商品`;
    }

    // 处理视图切换
    handleViewChange(view) {
        this.currentView = view;

        // 更新按钮状态
        document.querySelectorAll('.view-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelector(`[data-view="${view}"]`).classList.add('active');

        // 更新商品显示
        this.renderProducts();
    }

    // 处理分页
    handlePageChange(page) {
        if (page < 1 || page > this.totalPages) return;
        
        this.currentPage = page;
        this.loadProducts();
    }

    // 处理搜索
    handleSearch() {
        const keyword = document.getElementById('searchInput').value.trim();
        if (keyword) {
            window.location.href = `index.html?search=${encodeURIComponent(keyword)}`;
        }
    }

    // 加载商品
    async loadProducts() {
        try {
            console.log('开始加载商品...');
            this.showLoading();

            const params = {
                page: this.currentPage,
                limit: this.pageSize
            };

            if (this.currentCategory) {
                params.category = this.currentCategory;
            }

            console.log('请求参数:', params);
            const result = await api.getProducts(params);
            console.log('API响应:', result);

            if (result.success) {
                console.log('商品数据:', result.data.products);
                this.renderProducts(result.data.products);
                this.updatePagination(result.data);
            } else {
                console.error('API返回错误:', result.error);
                this.showToast('加载商品失败: ' + result.error, 'error');
            }

        } catch (error) {
            console.error('加载商品失败:', error);
            this.showToast('加载商品失败: ' + error.message, 'error');
        } finally {
            this.hideLoading();
        }
    }

    // 渲染商品
    renderProducts(products) {
        const productsGrid = document.getElementById('productsGrid');
        
        if (!products || products.length === 0) {
            productsGrid.innerHTML = `
                <div class="no-data">
                    <i class="fas fa-box"></i>
                    <p>暂无商品</p>
                </div>
            `;
            return;
        }

        if (this.currentView === 'grid') {
            productsGrid.innerHTML = products.map(product => `
                <div class="product-card" data-product-id="${product.id}">
                    <div class="product-image">
                        <img src="${product.image}" alt="${product.name}" loading="lazy">
                        <div class="product-overlay">
                            <button class="btn btn-primary btn-sm" onclick="productsPage.addToCart('${product.id}')">
                                <i class="fas fa-cart-plus"></i>
                                加入购物车
                            </button>
                        </div>
                    </div>
                    <div class="product-info">
                        <h3 class="product-name">${product.name}</h3>
                        <p class="product-price">¥${product.price.toFixed(2)}</p>
                        <p class="product-location">产地：${product.location}</p>
                        <div class="product-rating">
                            <div class="stars">
                                ${this.renderStars(product.average_rating)}
                            </div>
                            <span class="rating-text">${product.average_rating} (${product.review_count}评价)</span>
                        </div>
                        <button class="btn btn-outline btn-block" onclick="productsPage.viewProduct('${product.id}')">
                            查看详情
                        </button>
                    </div>
                </div>
            `).join('');
        } else {
            productsGrid.innerHTML = products.map(product => `
                <div class="product-list-item" data-product-id="${product.id}">
                    <div class="product-image">
                        <img src="${product.image}" alt="${product.name}" loading="lazy">
                    </div>
                    <div class="product-info">
                        <h3 class="product-name">${product.name}</h3>
                        <p class="product-description">${product.description}</p>
                        <p class="product-location">产地：${product.location}</p>
                        <div class="product-rating">
                            <div class="stars">
                                ${this.renderStars(product.average_rating)}
                            </div>
                            <span class="rating-text">${product.average_rating} (${product.review_count}评价)</span>
                        </div>
                    </div>
                    <div class="product-actions">
                        <p class="product-price">¥${product.price.toFixed(2)}</p>
                        <button class="btn btn-primary" onclick="productsPage.addToCart('${product.id}')">
                            <i class="fas fa-cart-plus"></i>
                            加入购物车
                        </button>
                        <button class="btn btn-outline" onclick="productsPage.viewProduct('${product.id}')">
                            查看详情
                        </button>
                    </div>
                </div>
            `).join('');
        }
    }

    // 渲染星级评分
    renderStars(rating) {
        const fullStars = Math.floor(rating);
        const hasHalfStar = rating % 1 >= 0.5;
        const emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0);

        let stars = '';
        
        // 满星
        for (let i = 0; i < fullStars; i++) {
            stars += '<i class="fas fa-star"></i>';
        }
        
        // 半星
        if (hasHalfStar) {
            stars += '<i class="fas fa-star-half-alt"></i>';
        }
        
        // 空星
        for (let i = 0; i < emptyStars; i++) {
            stars += '<i class="far fa-star"></i>';
        }
        
        return stars;
    }

    // 更新分页
    updatePagination(data) {
        this.totalPages = Math.ceil(data.total / this.pageSize);
        
        const prevBtn = document.getElementById('prevPage');
        const nextBtn = document.getElementById('nextPage');
        const pageNumbers = document.getElementById('pageNumbers');

        // 更新按钮状态
        prevBtn.disabled = this.currentPage <= 1;
        nextBtn.disabled = this.currentPage >= this.totalPages;

        // 生成页码
        pageNumbers.innerHTML = '';
        const startPage = Math.max(1, this.currentPage - 2);
        const endPage = Math.min(this.totalPages, this.currentPage + 2);

        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `page-number ${i === this.currentPage ? 'active' : ''}`;
            pageBtn.textContent = i;
            pageBtn.addEventListener('click', () => this.handlePageChange(i));
            pageNumbers.appendChild(pageBtn);
        }
    }

    // 添加到购物车
    async addToCart(productId) {
        try {
            const result = await api.addToCart(productId, 1);
            
            if (result.success) {
                this.showToast('商品已添加到购物车', 'success');
                this.updateCartCount();
            } else {
                this.showToast('添加失败', 'error');
            }
        } catch (error) {
            console.error('添加到购物车失败:', error);
            this.showToast('添加失败', 'error');
        }
    }

    // 查看商品详情
    viewProduct(productId) {
        window.location.href = `product-detail.html?id=${productId}`;
    }

    // 更新购物车数量
    async updateCartCount() {
        try {
            const result = await api.getCart();
            if (result.success) {
                const count = result.data.items ? result.data.items.length : 0;
                document.getElementById('cartCount').textContent = count;
            }
        } catch (error) {
            console.error('更新购物车数量失败:', error);
        }
    }

    // 更新用户状态
    updateUserStatus() {
        const user = JSON.parse(localStorage.getItem('currentUser'));
        
        if (user) {
            document.getElementById('userName').textContent = user.username;
            document.getElementById('loginBtn').style.display = 'none';
            document.getElementById('registerBtn').style.display = 'none';
            document.getElementById('userDivider').style.display = 'block';
            document.getElementById('profileBtn').style.display = 'block';
            document.getElementById('logoutBtn').style.display = 'block';
        } else {
            document.getElementById('userName').textContent = '登录';
            document.getElementById('loginBtn').style.display = 'block';
            document.getElementById('registerBtn').style.display = 'block';
            document.getElementById('userDivider').style.display = 'none';
            document.getElementById('profileBtn').style.display = 'none';
            document.getElementById('logoutBtn').style.display = 'none';
        }
    }

    // 显示登录模态框
    showLoginModal() {
        document.getElementById('loginModal').classList.add('show');
        document.body.style.overflow = 'hidden';
    }

    // 隐藏登录模态框
    hideLoginModal() {
        document.getElementById('loginModal').classList.remove('show');
        document.body.style.overflow = '';
        document.getElementById('loginForm').reset();
    }

    // 显示注册模态框
    showRegisterModal() {
        document.getElementById('registerModal').classList.add('show');
        document.body.style.overflow = 'hidden';
    }

    // 隐藏注册模态框
    hideRegisterModal() {
        document.getElementById('registerModal').classList.remove('show');
        document.body.style.overflow = '';
        document.getElementById('registerForm').reset();
    }

    // 处理登录
    async handleLogin() {
        try {
            const formData = new FormData(document.getElementById('loginForm'));
            const username = formData.get('username');
            const password = formData.get('password');

            const result = await api.login(username, password);

            if (result.success) {
                localStorage.setItem('currentUser', JSON.stringify(result.data));
                this.showToast('登录成功', 'success');
                this.hideLoginModal();
                this.updateUserStatus();
            } else {
                this.showToast(result.error || '登录失败', 'error');
            }
        } catch (error) {
            console.error('登录失败:', error);
            this.showToast('登录失败', 'error');
        }
    }

    // 处理注册
    async handleRegister() {
        try {
            const formData = new FormData(document.getElementById('registerForm'));
            const userData = {
                username: formData.get('username'),
                password: formData.get('password'),
                email: formData.get('email'),
                phone: formData.get('phone'),
                userType: formData.get('userType')
            };

            const result = await api.register(userData);

            if (result.success) {
                localStorage.setItem('currentUser', JSON.stringify(result.data));
                this.showToast('注册成功', 'success');
                this.hideRegisterModal();
                this.updateUserStatus();
            } else {
                this.showToast(result.error || '注册失败', 'error');
            }
        } catch (error) {
            console.error('注册失败:', error);
            this.showToast('注册失败', 'error');
        }
    }

    // 处理退出登录
    handleLogout() {
        localStorage.removeItem('currentUser');
        this.showToast('已退出登录', 'info');
        this.updateUserStatus();
    }

    // 显示加载状态
    showLoading() {
        const loading = document.getElementById('loading');
        if (loading) {
            loading.style.display = 'flex';
        }
    }

    // 隐藏加载状态
    hideLoading() {
        const loading = document.getElementById('loading');
        if (loading) {
            loading.style.display = 'none';
        }
    }

    // 显示消息提示
    showToast(message, type = 'info') {
        const toast = document.getElementById('toast');
        toast.textContent = message;
        toast.className = `toast toast-${type} show`;
        
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }
}

// 初始化商品分类页面
const productsPage = new ProductsPage();
